package com.bldby.baselibrary.core.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;

import java.util.List;

public class ApplicationUtil {

	private static final String UNKNOWN_APPLICATION_NAME = "unknown";
	private static final String UNKNOWN_APPLICATION_VERSION_NAME = "0.0.0";

	public static String getApplicationName(Context context) {
		int id = context.getApplicationInfo().labelRes;
		if (id > 0) {
			return context.getString(id);
		}
		return UNKNOWN_APPLICATION_NAME;
	}

	public static int getAvailableProcessors() {
		return Runtime.getRuntime().availableProcessors();
	}


	public static String getApplicationVersionName(Context context) {
		String pkgName = context.getPackageName();
		try {
			return context.getPackageManager().getPackageInfo(pkgName, 0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return UNKNOWN_APPLICATION_VERSION_NAME;
	}


	public static int getApplicationVersionCode(Context context) {
		String pkgName = context.getPackageName();
		try {
			return context.getPackageManager().getPackageInfo(pkgName, 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static String versionCodeToName(int versionCode) {
		int a = versionCode >> 16;
		int b = (versionCode - (a << 16)) >> 8;
		int c = versionCode % (1 << 8);
		return String.format("%d.%d.%d", a, b, c);
	}

	/**
	 * 方法描述：判断某一应用是否正在运行
	 *
	 * @param context     上下文
	 * @return true 表示正在运行，false表示没有运行
	 */
	public static boolean isAppRunning(Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
		if (list.size() <= 0) {
			return false;
		}
		for (ActivityManager.RunningTaskInfo info : list) {
			if (info.baseActivity.getPackageName().equals("com.gowithmi.mapworld")) {
				return true;
			}
		}
		return false;
	}

	public static boolean isApplicationInBackground(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses != null){
			for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
				if (appProcess.processName.equals(context.getPackageName())) {

					if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
						return false;
					}
				}
			}
		}
		return true;
	}

}
